﻿
$(function () {
    $('#TournamentId').change(function () {
        var tournamentId = $(this).val();
        if (tournamentId != "") {
            LoadTeams(tournamentId);
        }
    });

    $('.dateTime').each(function () { 
        $(this).datetimepicker();
    });

    $('#TeamA, #TeamB').each(function () {
        $(this).change(function () {
            ValidateScore(this);
        });
    });
});

function ValidateScore(element) {
    var score = $(element).val();
    var reg = new RegExp("^[0-9]+$");

    if (score == null || score == '' || !reg.test(score)) {
        $(element).val('0');
    }
    $('#upcomingGamesResult').hide();
}

function LoadTeams(tournamentId) {
    var formValues = $('#newGameForm').serialize();
    var url = "/Teams/GetTeamsByTournament";
    $.post(url, formValues, function (response) {
        for (i in response) {
            $('#TeamAId').append($("<option></option>").attr("value", response[i].Id).text(response[i].Name));
            $('#TeamBId').append($("<option></option>").attr("value", response[i].Id).text(response[i].Name));
        }
    });
}

function OpenMVPSelection(gameId) {
    var url = "/Games/MostValuablePlayer?gameId=" + gameId;

    var actions = {
        "Cancel": function () {
            $(this).dialog("close");
        }
    };

    $("#popup-message").html("<b>Loading...</b>").load(url);

    $("#popup-message").dialog({
        title: "Matches",
        modal: true,
        width: 800,
        height: 600,
        buttons: actions
    });
}

function SetMVP(playerName, playerId, teamName, gameId) {
    $('#popup-message').dialog("close");
    $('#MvpName-' + gameId).html(playerName + " (" + teamName + ")");
    $('#MvpId-' + gameId).val(playerId);
    $('#upcomingGamesResult').hide();
}

function ShowClosePreview() {
    var formValues = $('#CloseGameForm').serialize();
    var url = "/Games/ClosePreview";

    $.post(url, formValues, function (response) {
        $("#ClosePreview").html(response);
        $("#ClosePreviewFieldset").show();
    });
}
